package com.sys.service.impl;

import com.sys.dto.JwtResponse;
import com.sys.dto.LoginRequest;
import com.sys.dto.RegisterRequest;
import com.sys.exception.CustomException;
import com.sys.service.AuthService;
import com.sys.utils.JwtTokenUtil;
import com.sys.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sys.entity.User;
import com.sys.mapper.UserMapper;
import org.springframework.stereotype.Service;

/**
 * 认证服务的实现类
 */
@Service
public class AuthServiceImpl implements AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    private final JwtTokenUtil jwtTokenUtil;
    private final UserMapper userMapper;

    public AuthServiceImpl(JwtTokenUtil jwtTokenUtil, UserMapper userMapper) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userMapper = userMapper;
    }

    @Override
    public JwtResponse login(LoginRequest loginRequest) {
        // 参数验证
        if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
            throw new CustomException(1003, "用户名不能为空");
        }
        if (loginRequest.getPassword() == null || loginRequest.getPassword().isEmpty()) {
            throw new CustomException(1004, "密码不能为空");
        }

        // 1. 根据用户名从数据库查找用户
        User user = userMapper.findByUsername(loginRequest.getUsername());

        // 2. 检查用户是否存在
        if (user == null) {
            logger.warn("用户不存在: {}", loginRequest.getUsername());
            throw new CustomException(1001, "用户名不存在");
        }

        // 3. 验证密码
        logger.info("用户登录尝试 - 用户名: {}, 数据库密码哈希: {}", loginRequest.getUsername(), user.getPasswordHash());

        // 对输入密码进行MD5加密
        String encryptedPassword = MD5Util.encrypt(loginRequest.getPassword());
        logger.info("输入密码MD5加密后: {}", encryptedPassword);

        // 使用MD5加密请求密码并与数据库中的密码进行比较
        if (!encryptedPassword.equals(user.getPasswordHash())) {
            logger.warn("密码验证失败 - 用户名: {}", loginRequest.getUsername());
            throw new CustomException(1002, "密码错误");
        }

        logger.info("用户登录成功 - 用户名: {}", loginRequest.getUsername());

        // 4. 检查账户状态（例如，是否被锁定或禁用）
        // 此处可以添加更多逻辑

        // 5. 生成 JWT
        final String token = jwtTokenUtil.generateToken(user.getPhone());

        // 6. 返回 JWT
        return new JwtResponse(token, user.getUserType());
    }

    @Override
    public void register(RegisterRequest registerRequest) {
        logger.info("开始处理用户注册请求 - 用户名: {}", registerRequest.getUsername());
        
        // 1. 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(registerRequest.getUsername());
        if (existingUser != null) {
            logger.warn("注册失败 - 用户名已存在: {}", registerRequest.getUsername());
            throw new CustomException(1005, "用户名已存在");
        }

        // 2. 创建新用户对象
        User newUser = new User();
        newUser.setUsername(registerRequest.getUsername());
        newUser.setPhone(registerRequest.getUsername()); // 假设用户名就是手机号
        newUser.setName(registerRequest.getName());
        newUser.setPasswordHash(MD5Util.encrypt(registerRequest.getPassword()));
        newUser.setUserType(registerRequest.getUserType());
        newUser.setCreatedAt(new java.util.Date());
        newUser.setUpdatedAt(new java.util.Date());
        
        logger.info("准备插入新用户到数据库 - 用户名: {}, 姓名: {}, 用户类型: {}", 
                   newUser.getUsername(), newUser.getName(), newUser.getUserType());

        // 3. 插入新用户到数据库
        int result = userMapper.insert(newUser);
        
        if (result > 0) {
            logger.info("用户注册成功 - 用户ID: {}, 用户名: {}", newUser.getUserId(), newUser.getUsername());
        } else {
            logger.error("用户注册失败 - 用户名: {}", registerRequest.getUsername());
            throw new CustomException(1006, "注册失败，请稍后重试");
        }
    }
}